﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;

namespace SharpDB
{
    public static class Util
    {

        internal static DbType GetValueDbType(object objvalue, DbParameter para)
        {
            Type tyval = objvalue.GetType();
            Type typeVal = Nullable.GetUnderlyingType(tyval) ?? tyval;

            DbType dbType = DbType.AnsiString;
            DateTime dtime;
            Guid gid;
            if (typeVal.IsEnum && Enum.GetUnderlyingType(typeVal) == typeof(byte))
            {
                dbType = DbType.Int32;
            }
            else if (typeVal == typeof(byte[]))
            {
                dbType = DbType.Binary;
            }
            else if (DateTime.TryParse(objvalue.ToString(), out dtime)
               && !Regex.IsMatch(objvalue.ToString(), @"^\d{4}[.-/]{1}\d{1,2}$"))
            {
                dbType = DbType.DateTime;
            }
            else if (Guid.TryParse(objvalue.ToString(), out gid))
            {
                dbType = DbType.String;
                para.Value = objvalue.ToString();
            }
            else
            {

            }
            return dbType;
        }

        /// <summary>
        /// 拼接in sql语句
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="columnName">列名</param>
        /// <param name="values">元素值</param>
        /// <param name="isNotIn">not in 或 in </param>
        /// <returns></returns>
        public static string SqlIn<T>(string columnName, T[] values, bool isNotIn = false)
        {
            string result = string.Empty;
            if (values == null || values.Length <= 0)
            {
                return string.Empty;
            }
            List<string> lst = new List<string>();
            foreach (T obj in values)
            {
                if (obj != null)
                {
                    string val = obj.ToString();
                    if (val.StartsWith("'") && val.EndsWith("'"))
                    {
                        val = val.Replace("'", "'''");
                        lst.Add(val);
                        continue;
                    }
                    lst.Add("'" + val + "'");
                }
            }
            if (lst.Count > 0)
            {
                result = " and " + columnName + " " + (isNotIn ? "not" : "") + " in (" + string.Join(",", lst) + ") ";
            }
            return result;
        }

        /// <summary>
        /// 拼接多条 like 语句
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="columnName">列名</param>
        /// <param name="values">元素值</param>
        /// <param name="isOrLike">or like 或 and like</param>
        /// <returns></returns>
        public static string SqlLike<T>(string columnName, T[] values, bool isOrLike = true)
        {
            string result = string.Empty;
            if (values == null || values.Length <= 0)
            {
                return string.Empty;
            }
            List<string> lst = new List<string>();
            foreach (T obj in values)
            {
                if (obj != null)
                {
                    string like_sql = columnName + " like '%{0}%' ";
                    string temp_sql = string.Empty;
                    string val = obj.ToString();
                    if (val.StartsWith("'") && val.EndsWith("'"))
                    {
                        val = val.Replace("'", "''");
                        temp_sql = string.Format(like_sql, val);
                        lst.Add(temp_sql);
                        continue;
                    }
                    temp_sql = string.Format(like_sql, val);
                    lst.Add(temp_sql);
                }
            }
            if (lst.Count>0)
            {
                result = " and (" + (string.Join((isOrLike ? " or" : " and "), lst)) + ") ";
            }            
            return result;
        }


        /// <summary>
        /// 凭借执行异常的Sql
        /// </summary>
        /// <param name="strSql"></param>
        /// <param name="cmdParms"></param>
        /// <returns></returns>
        public static string PinJieExSql(string strSql, params IDataParameter[] cmdParms)
        {
            string ex_sql = strSql;
            if (cmdParms != null && cmdParms.Length > 0)
            {
                foreach (var item in cmdParms)
                {
                    string val = string.Empty;
                    val = "'" + item.Value + "'";
                    //if (item.DbType != DbType.Binary || item.DbType != DbType.Byte)
                    //{

                    //}
                    ex_sql = ex_sql.Replace(item.ParameterName, val);
                }
            }
            return ex_sql;
        }



        /// <summary>  
        /// 把一个一维数组转换为DataTable  
        /// </summary>  
        public static DataTable Convert(string ColumnName, string[] Array)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add(ColumnName, typeof(string));

            for (int i = 0; i < Array.Length; i++)
            {
                DataRow dr = dt.NewRow();
                dr[ColumnName] = Array[i].ToString();
                dt.Rows.Add(dr);
            }
            return dt;
        }



        /*
         * 
         * 
           string[,] arr =
            {
                { "A1","A2","A3" },
                { "B1","B2","B3" },
            };
            DataTable dtTemp = SharpDB.Util.Convert(new string[] { "列1", "列2", "列3" }, arr);

         * 
         */
        /// <summary>  
        /// 反一个M行N列的二维数组转换为DataTable  
        /// </summary>  
        public static DataTable Convert(string[] ColumnNames, string[,] Arrays)
        {
            DataTable dt = new DataTable();

            foreach (string ColumnName in ColumnNames)
            {
                dt.Columns.Add(ColumnName, typeof(string));
            }

            for (int i1 = 0; i1 < Arrays.GetLength(0); i1++)
            {
                DataRow dr = dt.NewRow();
                for (int i = 0; i < ColumnNames.Length; i++)
                {
                    dr[i] = Arrays[i1, i].ToString();
                }
                dt.Rows.Add(dr);
            }
            return dt;
        }

    }
}
